import Socket from './socket'
import EventEmitter from './EventEmitter'
export default class Room extends EventEmitter {
  constructor (opts) {
    super()
    opts = opts || {}
    this.roomId = opts.roomId || ''
    this.platform = opts.platform || ''
    this.users = []
    this.chatMessages = []
    this.gift = {}
    this.timer = null
    this.socket = new Socket(opts.roomId)
    this._init()
    this.data = null
    this.chart = {}
    this.chartTimer = null
    this.chartStr = ['users', 'msgs', 'chat', 'fins', 'gifts', 'online']
    this.colors = ['#11cd6e', '#56abe4', '#9d55b8', '#ea8010', '#eb4f38', '#33475f', '#00bb9c', '#f4c600', '#000000']
    this.chartTitle = {
      'users': {
        label: '人数变动',
        color: this.colors[0]
      },
      'msgs': {
        label: '弹幕总计',
        color: this.colors[1]
      },
      'chat': {
        label: '发言人数',
        color: this.colors[2]
      },
      'fins': {
        label: '鱼翅总计',
        color: this.colors[3]
      },
      'gifts': {
        label: '礼物总计',
        color: this.colors[4]
      },
      'online': {
        label: '观看人数',
        color: this.colors[5]
      }
    }
  }
  _init () {
    this.socket.on('initRoom', this.onInitRoom.bind(this))
    this.socket.on('roomUpdate', this.onRoomUpdate.bind(this))
    this.socket.on('chatMsg', this.onChatMsg.bind(this))
    this.socket.on('changeState', this.onChangeState.bind(this))
  }
  onChangeState (code) {
    if (this.data && this.data.state.msg !== '未开播') {
      var state = this._getState(code)
      this.data.state.code = state.code
      this.data.state.msg = state.msg
    }
  }
  _getState (code) {
    switch (code) {
      case 0:
        return {
          code: 3,
          msg: '已连接'
        }
      case 1:
        return {
          code: 0,
          msg: '连接中'
        }
      case 2:
        return {
          code: 2,
          msg: '已断开'
        }
      case 3:
        return {
          code: 2,
          msg: '已断开'
        }
      case 4:
        return {
          code: 3,
          msg: '已连接'
        }
      case 5:
        return {
          code: 0,
          msg: '连接中'
        }
      case 6:
        return {
          code: 2,
          msg: '已断开'
        }
      case 7:
        return {
          code: 0,
          msg: '绑定中'
        }
      case 8:
        return {
          code: 1,
          msg: '已暂停'
        }
      case 9:
        return {
          code: 3,
          msg: '直播中'
        }
      default:
        return null
    }
  }
  onInitRoom (info) {
    if (info && info.error === 0) {
      this.data = {
        users: 0,
        msgs: 0,
        chat: 0,
        fishBalls: 0,
        fins: 0,
        gifts: 0,
        time: 0,
        online: 0,
        count: {},
        startTime: this.getTime(),
        state: {
          code: 0,
          msg: '连接中'
        }
      }
      this._initGift(this.gift, info.data.gift)
      this.data.online = info.data.online
      this.info = {
        avatar: info.data.avatar,
        roomName: info.data.room_name,
        roomUrl: this.platform + this.roomId,
        roomId: info.data.room_id,
        nick: info.data.owner_name,
        fans: info.data.fans_num,
        online: info.data.online,
        weight: info.data.owner_weight
      }
      if (info.data.room_status === '2') {
        this.data.state.code = 2
        this.data.state.msg = '未开播'
      } else {
        this.data.state.code = 3
        this.data.state.msg = '直播中'
        this._onTimer()
        setTimeout(function () {
          this._chartTimer()
        }, 1000 * 60)
      }
      this._initGift(this.data.count, info.data.gift)
      this.chart.users = []
      this.chart.msgs = []
      this.chart.chat = []
      this.chart.fishBalls = []
      this.chart.fins = []
      this.chart.gifts = []
      this.chart.online = []
      this.chart.time = []
      for (var i = 0; i < info.data.gift.length; i++) {
        this.chart[info.data.gift[i].id] = []
      }
    }
    this.emit('init', info)
  }
  _onTimer () {
    clearTimeout(this.timer)
    this.data.time += 1
    this.timer = setTimeout(this._onTimer.bind(this), 1000)
  }
  _chartTimer () {
    clearTimeout(this.chartTimer)
    this.onChart()
    this.chartTimer = setTimeout(this._chartTimer.bind(this), 1000 * 60)
  }
  onChart () {
    var time = this.getTime()
    this.chart.time.push(time)
    for (var key in this.data) {
      if (this.data.hasOwnProperty(key)) {
        if (key === 'count') {
          for (var k in this.data[key]) {
            if (this.data[key].hasOwnProperty(k)) {
              this._push(this.chart[k], this.data[key][k].count, time)
            }
          }
        } else if (key === 'online') {
          this.chart[key].push({
            time: time,
            count: this.data[key]
          })
        } else if (key === 'users') {
          if (this.chartStr.indexOf(key) > -1) {
            if (this.chart[key].length > 0) {
              this._push(this.chart[key], this.data.online, time)
            } else {
              this.chart[key].push({
                time: time,
                lastNum: this.data.online,
                count: 0
              })
            }
          }
        } else {
          if (this.chartStr.indexOf(key) > -1) {
            this._push(this.chart[key], this.data[key], time)
          }
        }
      }
    }
  }
  _push (arr, count, time) {
    var num = count
    if (arr.length > 0) {
      var lastObj = arr[arr.length - 1]
      num = count - lastObj.lastNum
    }
    arr.push({
      time: time,
      lastNum: count,
      count: num
    })
  }

  onRoomUpdate (info) {
    this.info.fans = info.data.fans_num
    this.info.online = info.data.online
    this.info.weight = info.data.owner_weight
    this.data.online = info.data.online
    if (info.data.room_status === '2') {
      this.data.state.code = 2
      this.data.state.msg = '未开播'
      clearTimeout(this.chartTimer)
      clearTimeout(this.timer)
    } else {
      this.data.state.code = 3
      this.data.state.msg = '直播中'
      this._onTimer()
      this._chartTimer()
    }
  }
  onChatMsg (msg) {
    if (msg && this[msg.type]) {
      this[msg.type](msg)
    } else {
      if (msg.type === 'rss') {
        this.data.state.code = 2
        this.data.state.msg = '未开播'
        clearTimeout(this.chartTimer)
        clearTimeout(this.timer)
      }
    }
  }
  getOnLineChart () {
    return this.getChart(['online', 'users'], 'line')
  }
  getContrastChart () {
    return this.getChart(['msgs', 'chat', 'fins', 'gifts'], 'line')
  }
  getGiftChart () {
    let data = {
      labels: [],
      datasets: [{
        data: [],
        backgroundColor: []
      }]
    }
    let index = 0
    for (var key in this.gift) {
      if (this.gift.hasOwnProperty(key)) {
        data.labels.push(this.gift[key].name)
        data.datasets[0].data.push(this.data.count[this.gift[key].id].count)
        data.datasets[0].backgroundColor.push(this.colors[index])
        index += 1
      }
    }
    return {
      type: 'pie',
      data: data
    }
  }
  getChart (chartStr, type) {
    var datas = []
    for (var key in this.data) {
      if (this.data.hasOwnProperty(key)) {
        if (key !== 'count') {
          if (chartStr.indexOf(key) > -1) {
            datas.push({
              label: this.chartTitle[key].label,
              fill: false,
              backgroundColor: this.chartTitle[key].color,
              borderColor: this.chartTitle[key].color,
              data: this.chart[key].map(function (item) {
                return item.count
              })
            })
          }
        }
      }
    }
    return {
      type: type,
      data: {
        labels: this.chart.time,
        datasets: datas
      }
    }
  }
  getTime () {
    var date = new Date()
    var minut = date.getMinutes()
    return date.getHours() + ':' + (minut >= 10 ? minut : '0' + minut)
  }
  _initGift (obj, gift) {
    for (var i = 0; i < gift.length; i++) {
      obj[gift[i].id] = {
        name: gift[i].name,
        pc: gift[i].pc,
        type: gift[i].type,
        id: gift[i].id,
        count: 0
      }
    }
  }
  _initUser (data) {
    if (this._findUser(data) === -1) {
      var user = {
        uid: data.uid,
        ic: 'http://uc.douyutv.com/upload/' + data.ic + '_middle.jpg?rltime',
        level: data.level,
        nn: data.nn,
        msgs: 0, // 发送信息总数
        msgs_lastTime: '',
        fishBalls: 0,
        fishBalls_lastTime: '',
        fins: 0, // 总鱼翅数量
        fins_lastTime: '',
        gifts: 0, // 赠送礼物次数
        gifts_lastTime: ''
      }
      for (var key in this.gift) {
        if (this.gift.hasOwnProperty(key)) {
          user[this.gift[key].id] = 0
          user[this.gift[key].id + '_lastTime'] = ''
        }
      }
      this.users.push(user)
      return true
    }
    return false
      //  console.log(this.users)
  }
  _findUser (data) {
    var index = -1
    this.users.some(function (item, number) {
      if (item.uid === data.uid) {
        index = number
        return true
      }
      return false
    })
    return index
  }
  uenter (data) {
    this.data.users += 1
    this._initUser(data)
  }
  chatmsg (data) {
    this.emit('chat', data)
    if (this.chatMessages.length > 500) {
      this.chatMessages.splice(0, 1)
    }
    this.chatMessages.push(data)
    this.data.msgs += 1
    if (this._initUser(data)) {
      this.data.chat += 1
    }
    var index = this._findUser(data)
    this.users[index].msgs += 1
    this.users[index].msgs_lastTime = data.serverdate
  }
  dgb (data) {
    this._initUser(data)
    this.data.gifts += 1
    var index = this._findUser(data)
    this.users[index].gifts += 1
    this.users[index].gifts_lastTime = data.serverdate
    this.data.count[data.gfid].count += 1
    this.users[index][data.gfid] += 1
    this.users[index][data.gfid + '_lastTime'] = data.serverdate
    var self = this
    this.data.fins = this._compute(function (id) {
      return self.data.count[id].count
    })
    this.users[index].fins = this._compute(function (id) {
      return self.users[index][id]
    })
  }
  _compute (fn) {
    var count = 0.0
    for (var key in this.gift) {
      if (this.gift.hasOwnProperty(key)) {
        if (this.gift[key].type === '2') {
          count += this.gift[key].pc * fn(this.gift[key].id)
        }
      }
    }
    return count
  }
  filter (field) { // 排序
    if (field !== 'uid' && field !== 'ic' && field !== 'nn') {
      this.users.sort(function (a, b) {
        return b[field] - a[field]
      })
    }
    return this.users.slice(0, 100)
      .filter(function (item) {
        if (item[field] > 0) {
          return true
        }
        return false
      })
  }
  stop () {
    if (this.data.state.code === 3) {
      if (this.socket) {
        this.socket.stop(this.roomId)
        if (this.timer) {
          clearTimeout(this.timer)
        }
      }
    }
  }
  remove () {
    if (this.socket) {
      this.socket.remove()
      if (this.timer) {
        clearTimeout(this.timer)
        clearTimeout(this.chartTimer)
      }
    }
  }
  start () {
    var self = this
    if (self.data.state.code === 1) {
      if (self.socket) {
        self.socket.start(self.roomId)
        self._onTimer()
      }
    }
  }
}
